<?php defined('SYSPATH') or die('No direct script access.');

class Model_Brand extends ORM
{  
    protected $_reload_on_wakeup = false;
    
    protected static function _compare($a, $b)
    {
        return $a['count'] < $b['count'];
    }
    
    public function get_brands(Model_Category $category, $color = null, $composition = null, $season = null, $shop = null, $price = null, $limit = 7)
    {        
        $stat = array();
        $ids = array(); 
        if ($category->childs) {
            $ids = explode(',', $category->childs);    
        }
        $ids[] = $category->id;
        
        $color_id = $color;
        if (is_array($color)) {
            $color_id = $color['id'];   
        }
        
        $composition_id = $composition;
        if (is_array($composition)) {
            $composition_id = $composition['id'];    
        }
        
        $season_id = $season;
        if (is_array($season)) {
            $season_id = $season['id'];    
        }
        
        $shop_id = $shop;
        if (is_array($shop)) {
            $shop_id = $shop['id'];   
        }
        
        $from_price = $to_price = null;
        if (isset($price['from']) && $price['from']) {
            $from_price = $price['from'];    
        }
        if (isset($price['to']) && $price['to']) {
            $to_price = $price['to'];    
        }
        
        if ($brands = Cache::instance()->get('category_brands_'.$category->id.'_'.$color_id.'_'.$composition_id.'_'.$season_id.'_'.$shop_id.'_'.$from_price.'_'.$to_price)) {
            return $brands;
        }
        
        $tmp_stat = DB::select('brand_id', array(DB::expr('COUNT( * )'), 'count'))
                    ->from('products')
                    ->where('category_id', 'IN', $ids)
                    ->where('available', '=', 1);
                    
        if ($color_id) {
            $tmp_stat->join('product_colors', 'LEFT')
                  ->on('product_colors.product_id', '=', 'products.id')
                  ->where('product_colors.color_id', '=', $color_id);    
        }
        
        if ($composition_id) {
            $tmp_stat->join('product_compositions', 'LEFT')
                  ->on('product_compositions.product_id', '=', 'products.id')
                  ->where('product_compositions.composition_id', '=', $composition_id);   
        }
        
        if ($season_id) {
            $tmp_stat->join('product_seasons', 'LEFT')
                  ->on('product_seasons.product_id', '=', 'products.id')
                  ->where('product_seasons.season_id', '=', $season_id);   
        }
        
        if ($shop_id) {
            $tmp_stat->where('shop_id', '=', $shop_id);    
        }
        
        if ($from_price) {
            $tmp_stat->where('price', '>=', $from_price);    
        }
        if ($to_price) {
            $tmp_stat->where('price', '<=', $to_price); 
        }
                    
        $tmp_stat = $tmp_stat
                    ->group_by('brand_id')
                    ->order_by('count', 'DESC')
                    ->execute()
                    ->as_array();
        
        $ids = array();
        foreach ($tmp_stat as $item) {
            $ids[] = $item['brand_id'];
            $stat[$item['brand_id']] = $item['count'];    
        }
        if (!count($ids)) {
            return null;    
        }
        $brands = array();
        $tmp_brands = ORM::factory('brand')
                        ->where('id', 'IN', $ids)
                        ->find_all()
                        ->as_array();
        foreach ($tmp_brands as $brand) {
            $brand = $brand->as_array(); 
            $brands[$brand['id']] = $brand;
            $brands[$brand['id']]['count'] = $stat[$brand['id']];            
        } 
        usort($brands, array(__CLASS__, '_compare'));  
        
        $result = array(
            'main'  => array(),
            'other' => array(),
        );
        $i = 0;
        foreach ($brands as $brand) {
            if ($i < $limit) {
                $result['main'][] = $brand;         
            } else {
                $result['other'][] = $brand;    
            } 
            $i++;   
        }   
        
        Cache::instance()->set('category_brands_'.$category->id.'_'.$color_id.'_'.$composition_id.'_'.$season_id.'_'.$shop_id.'_'.$from_price.'_'.$to_price, $result);
        return $result;                                              
    }
    
    public function get_brand_by_url($url)
    {
        $brand = ORM::factory('brand')->where('url', '=', $url)->find();
        if (!$brand->loaded()) {
            throw new HTTP_Exception_404('Запись не найдена');      
        }
        return $brand;
    }
    
}